package com.example.module.Controller;

import com.example.module.Common.BaseResponse;
import com.example.module.Common.BusinessException;
import com.example.module.enums.RedisKey;
import com.example.module.enums.StatusCode;
import com.example.module.service.EmailService;
import com.example.module.service.VerificationCodeService;
import com.example.module.util.RegExpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName EmailController
 * @Description 类注释
 * @Author 开发者
 * @Date 2023-05-09 16:19
 */
@RestController
public class EmailController {

    //设置验证码过期时间
    private final Integer EMAIL_EXPIRED_TIME = 5;

    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private EmailService emailService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @PostMapping("/code")
    public BaseResponse<String> sendMessageToEmail(@RequestParam("email") String email) {
        if (StringUtils.isAnyBlank(email)) {
            throw new BusinessException(StatusCode.NULL_ERROR, "邮箱为空");
        }
        // 校验邮箱
        if(!RegExpUtil.checkEmail(email))
            return BaseResponse.error("邮箱格式错处");

//        // 从redis中查看有没有该邮箱的验证码
        String verifyCode = (String) redisTemplate.opsForValue().get(RedisKey.EMAIL_CODE + email);
        if (!StringUtils.isAnyBlank(verifyCode)) {
            throw new BusinessException(StatusCode.SUCCESS, "验证码已发送=>" + verifyCode);
        }
//        // 如果redis没有该手机号验证码，则获取验证码并发送短信
        verifyCode = verificationCodeService.generateVerificationCode(); // 获取六位验证码
        emailService.sendMessageToEmail(verifyCode, email);
//        // 将该验证码存入redis
        redisTemplate.opsForValue().set(
                RedisKey.EMAIL_CODE + email,
                verifyCode,
                EMAIL_EXPIRED_TIME,
                TimeUnit.MINUTES);
        return BaseResponse.success("发送成功");
    }

}
